<?php
//+---------------------------------------------------------------------------------------------------------------------
//| 人生是荒芜的旅行，冷暖自知，苦乐在心
//+---------------------------------------------------------------------------------------------------------------------
//| Author:Janmas <janmas@126.com>
//+---------------------------------------------------------------------------------------------------------------------
//| 
//+---------------------------------------------------------------------------------------------------------------------


namespace helper\upload;


use OSS\Core\OssException;
use OSS\OssClient;
use think\Exception;
use think\facade\Filesystem;
use think\File;

class AliOss extends BaseUpload
{
    public function upload(File $file=null,$justGetFileName=false)
    {
        $this->validate($file);
        $ossClient = new OssClient($this->config['accessKey'],$this->config['accessKeySecret'],$this->config['endpoint']);
        $filename = date('Ymd') . '/' . $file->getOriginalName();
        $result = $ossClient->uploadFile($this->config['bucket'],$filename,$file->getPathname());
        if($result['info']['http_code'] !== 200){
            throw new \Exception('上传文件失败');
        }
        if($justGetFileName){
            $this->fileInfo['path'] =  $filename;
        }else{
            $this->fileInfo['path'] =  $this->config['domain'].'/'.$filename;
        }
        $this->fileInfo['thumb'] = $this->isVideo($file)?$this->fileInfo['path'] . '?x-oss-process=video/snapshot,t_7000,f_jpg,w_800,h_600,m_fast':'';
        return $this->fileInfo;
    }

	/**
     * 不用了 该方法废弃
	 * @inheritDoc
	 */
	public function uploadFile( File $file = null,$justGetFileName=false )
	{
		try{
			/**
			 * @var Filesystem $fInfo
			 */
			$fInfo = $this->save($file);
			if(!$fInfo){
				throw new Exception('上传文件失败');
			}
			$ossClient = new OssClient($this->config['accessKey'],$this->config['accessKeySecret'],$this->config['endpoint']);
			$handle = fopen($fInfo, 'r');
			$filename = uniqid().$file->getOriginalName();
			$res = $ossClient->uploadStream($this->config['bucket'],$filename,$handle,[OssClient::OSS_CONTENT_DISPOSTION=>'inline; filename='.$file->getOriginalName()]);
			if($res['info']['http_code'] !== 200){
				throw new OssException('上传文件失败');
			}
            fclose($handle);
			unlink('./'.$fInfo);

			if($justGetFileName){
				$this->fileInfo['path'] =  $filename;
			}else{
				$this->fileInfo['path'] =  $this->config['domain'].'/'.$filename;
			}
			$this->fileInfo['thumb'] = $this->isVideo($file)?$this->fileInfo['path'] . '?x-oss-process=video/snapshot,t_7000,f_jpg,w_800,h_600,m_fast':'';
			return self::$instance;
		} catch(OssException $e) {
			throw new Exception($e->getMessage());
		}
	}



}